'use strict'
const {Blog,Op}=require('../model');
let fn_list=async(ctx,next)=>{
let keyword=ctx.request.query.keyword;
console.log(keyword);
if(keyword){
    let list=await Blog.findAll({where:{
        [Op.or]:[
            {title:keyword},
            {digest:keyword},
            {content:keyword},
            {classify:keyword},
            {timedate:keyword},
        ]
    },
    order:['id']
})
ctx.body={
    code:1000,
    data:list,
    msg:'请求成功'
}
}else{
    let list=await Blog.findAll({
        order:['id']
    })
    ctx.body={
        code:1000,
        data:list,
        msg:'请求失败'
    }
}
}
let fn_getbyid=async(ctx,next)=>{
let id=ctx.request.params.id;
let blogs=await Blog.findByPk(id);
if(blogs){
    ctx.body={
        code:1000,
        data:blogs,
        msg:'获取成功'
    }
}else{
    ctx.body={
        code:4000,
        data:'',
        msg:'获取失败'
    }
}
}
let fn_post=async(ctx,next)=>{
let obj=ctx.request.body;
await Blog.create(obj);
ctx.body=obj;
}
let fn_put=async(ctx,next)=>{
    let id=ctx.request.body.id;
    let obj=ctx.request.body;
    let blogs=await Blog.findByPk(id);
    if(blogs){
        Blog.update(obj,{
            where:{
                id:id
            }
        })
        ctx.body={
            code:1000,
            data:blogs,
            msg:'修改成功'
        }
    }else{
        ctx.body={
            code:4000,
            data:'',
            msg:'修改失败'
        }
    }
}
let fn_delete=async(ctx,next)=>{
    let id=ctx.request.body.id;
    let blogs=await Blog.findByPk(id);
    if(blogs){
        Blog.destroy({
            where:{
                id:id
            }
        })
        ctx.body={
            code:1000,
            data:blogs,
            msg:'删除成功'
        }
    }else{
        ctx.body={
            code:4000,
            data:null,
            msg:'删除失败'
        }
    }
}
module.exports={
    'get /blog':fn_list,
    'get /blog/:id':fn_getbyid,
    'post /blog':fn_post,
    'put /blog/:id':fn_put,
    'delete /blog/:id':fn_delete,

}